import { Service } from '../types/index.js';

/**
 * 权限管理服务
 * 负责用户认证、权限检查、路由守卫等功能
 */
class AuthService extends Service {
  constructor(container) {
    super(container);
    this.authConfig = container.getConfig('admin.auth');
    this.routerConfig = container.getConfig('admin.router');
    this.cacheConfig = container.getConfig('admin.cache');
    this.userInfo = null;
    this.token = null;
    this.tokenExpire = null;
    this.permissions = new Set();
    this.roles = new Set();
    this.events = new Map();
    
    // 初始化
    this.init();
  }

  /**
   * 初始化认证状态
   */
  init() {
    this.loadToken();
    this.loadUserInfo();
  }

  /**
   * 从缓存加载token
   */
  loadToken() {
    const storage = this.getStorage();
    if (storage) {
      this.token = storage.getItem(this.authConfig.tokenKey);
      this.tokenExpire = storage.getItem(this.authConfig.tokenExpireKey);
    }
  }

  /**
   * 保存token到缓存
   */
  saveToken(token, expireTime) {
    const storage = this.getStorage();
    if (storage) {
      storage.setItem(this.authConfig.tokenKey, token);
      if (expireTime) {
        storage.setItem(this.authConfig.tokenExpireKey, expireTime);
        this.tokenExpire = expireTime;
      }
    }
    this.token = token;
  }

  /**
   * 从缓存加载用户信息
   */
  loadUserInfo() {
    const storage = this.getStorage();
    if (storage) {
      const userInfoStr = storage.getItem(this.authConfig.userInfoKey);
      if (userInfoStr) {
        try {
          this.userInfo = JSON.parse(userInfoStr);
          this.updatePermissions(this.userInfo.permissions || []);
          this.updateRoles(this.userInfo.roles || []);
        } catch (error) {
          console.error('Failed to parse user info:', error);
        }
      }
    }
  }

  /**
   * 保存用户信息到缓存
   */
  saveUserInfo(userInfo) {
    this.userInfo = userInfo;
    const storage = this.getStorage();
    if (storage) {
      storage.setItem(this.authConfig.userInfoKey, JSON.stringify(userInfo));
    }
    this.updatePermissions(userInfo.permissions || []);
    this.updateRoles(userInfo.roles || []);
  }

  /**
   * 更新权限列表
   */
  updatePermissions(permissions) {
    this.permissions.clear();
    permissions.forEach(perm => this.permissions.add(perm));
  }

  /**
   * 更新角色列表
   */
  updateRoles(roles) {
    this.roles.clear();
    roles.forEach(role => this.roles.add(role));
  }

  /**
   * 获取存储对象
   */
  getStorage() {
    return this.cacheConfig.storageType === 'localStorage' ? localStorage : sessionStorage;
  }

  /**
   * 登录方法
   */
  async login(username, password, remember = false) {
    try {
      const apiService = this.container.get('api');
      const response = await apiService.post(this.authConfig.loginUrl, {
        username,
        password
      });

      if (response.code === 200 && response.data) {
        const { token, expireTime, userInfo } = response.data;
        
        // 保存token和用户信息
        this.saveToken(token, expireTime);
        this.saveUserInfo(userInfo);
        
        // 触发登录成功事件
        this.emit('loginSuccess', userInfo);
        
        return { success: true, userInfo };
      }
      
      return { success: false, message: response.message || 'Login failed' };
    } catch (error) {
      console.error('Login error:', error);
      return { success: false, message: error.message || 'Network error' };
    }
  }

  /**
   * 登出方法
   */
  logout(redirect = true) {
    // 清除token和用户信息
    const storage = this.getStorage();
    if (storage) {
      storage.removeItem(this.authConfig.tokenKey);
      storage.removeItem(this.authConfig.refreshTokenKey);
      storage.removeItem(this.authConfig.tokenExpireKey);
      storage.removeItem(this.authConfig.userInfoKey);
    }

    this.token = null;
    this.tokenExpire = null;
    this.userInfo = null;
    this.permissions.clear();
    this.roles.clear();

    // 触发登出事件
    this.emit('logoutSuccess');

    // 重定向到登录页面
    if (redirect && window && this.routerConfig) {
      window.location.href = this.routerConfig.loginPath;
    }
  }

  /**
   * 检查是否已登录
   */
  isLoggedIn() {
    return !!this.token && !!this.userInfo && !this.isTokenExpired();
  }

  /**
   * 检查token是否过期
   */
  isTokenExpired() {
    if (!this.tokenExpire) return false;
    return Date.now() > parseInt(this.tokenExpire, 10);
  }

  /**
   * 检查是否有权限
   */
  hasPermission(permission) {
    return this.permissions.has(permission);
  }

  /**
   * 检查是否有任一权限
   */
  hasAnyPermission(permissions) {
    return permissions.some(perm => this.hasPermission(perm));
  }

  /**
   * 检查是否有所有权限
   */
  hasAllPermissions(permissions) {
    return permissions.every(perm => this.hasPermission(perm));
  }

  /**
   * 检查是否有角色
   */
  hasRole(role) {
    return this.roles.has(role);
  }

  /**
   * 检查是否有任一角色
   */
  hasAnyRole(roles) {
    return roles.some(role => this.hasRole(role));
  }

  /**
   * 获取当前用户信息
   */
  getUserInfo() {
    return this.userInfo;
  }

  /**
   * 获取token
   */
  getToken() {
    return this.token;
  }

  /**
   * 注册事件监听器
   */
  on(event, callback) {
    if (!this.events.has(event)) {
      this.events.set(event, []);
    }
    this.events.get(event).push(callback);
  }

  /**
   * 移除事件监听器
   */
  off(event, callback) {
    if (this.events.has(event)) {
      if (callback) {
        const callbacks = this.events.get(event);
        const index = callbacks.indexOf(callback);
        if (index > -1) {
          callbacks.splice(index, 1);
        }
      } else {
        this.events.delete(event);
      }
    }
  }

  /**
   * 触发事件
   */
  emit(event, ...args) {
    if (this.events.has(event)) {
      this.events.get(event).forEach(callback => {
        try {
          callback(...args);
        } catch (error) {
          console.error(`Error in event handler for ${event}:`, error);
        }
      });
    }
  }

  /**
   * 获取路由守卫函数
   */
  getRouteGuard() {
    const auth = this;
    
    return {
      /**
       * 前置守卫
       */
      beforeEach: (to, from, next) => {
        // 无需认证的路由
        if (to.meta && to.meta.requiresAuth === false) {
          return next();
        }

        // 检查登录状态
        if (!auth.isLoggedIn()) {
          return next({
            path: auth.routerConfig.loginPath,
            query: { redirect: to.fullPath }
          });
        }

        // 检查权限
        if (to.meta && to.meta.permission) {
          if (!auth.hasPermission(to.meta.permission)) {
            return next(auth.routerConfig.forbiddenPath);
          }
        }

        // 检查角色
        if (to.meta && to.meta.role) {
          if (!auth.hasRole(to.meta.role)) {
            return next(auth.routerConfig.forbiddenPath);
          }
        }

        next();
      }
    };
  }

  /**
   * 创建权限指令
   */
  createPermissionDirective(app) {
    // v-permission 指令
    app.directive('permission', {
      mounted(el, binding) {
        const hasPerm = binding.value;
        if (hasPerm && !this.hasPermission(hasPerm)) {
          el.style.display = 'none';
        }
      },
      updated(el, binding) {
        const hasPerm = binding.value;
        if (hasPerm && !this.hasPermission(hasPerm)) {
          el.style.display = 'none';
        } else {
          el.style.display = '';
        }
      }
    });

    // v-role 指令
    app.directive('role', {
      mounted(el, binding) {
        const hasRole = binding.value;
        if (hasRole && !this.hasRole(hasRole)) {
          el.style.display = 'none';
        }
      },
      updated(el, binding) {
        const hasRole = binding.value;
        if (hasRole && !this.hasRole(hasRole)) {
          el.style.display = 'none';
        } else {
          el.style.display = '';
        }
      }
    });
  }

  /**
   * 启动服务
   */
  boot() {
    console.log('AuthService booted');
    
    // 定期检查token是否过期
    this.tokenCheckInterval = setInterval(() => {
      if (this.isLoggedIn() && this.isTokenExpired()) {
        this.logout();
      }
    }, 60000); // 每分钟检查一次
  }

  /**
   * 关闭服务
   */
  shutdown() {
    console.log('AuthService shutdown');
    if (this.tokenCheckInterval) {
      clearInterval(this.tokenCheckInterval);
    }
  }
}

export default AuthService;